package xin.nick.system.manager;


import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.AES;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jose4j.jwt.JwtClaims;
import org.jose4j.jwt.consumer.InvalidJwtException;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import xin.nick.common.core.constant.SystemConstants;
import xin.nick.common.core.util.JwtUtil;
import xin.nick.common.core.util.MyAssert;
import xin.nick.system.config.ApplicationSystemProperties;
import xin.nick.system.domain.vo.LoginUserVO;
import xin.nick.system.entity.SystemUser;

import java.util.concurrent.TimeUnit;

/**
 * @author Nick
 * @since 2022/12/5/005
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class LoginManager {

    private final RedisTemplate<String, Object> redisTemplate;
    private final ApplicationSystemProperties systemProperties;

    /**
     * 移除登录用户token
     * @param userId
     * @return
     */
    public Boolean removeLoginUserToken(Long userId) {
        // 移除登录用户的token
        String tokenKey = SystemConstants.USER_TOKEN_KEY + userId;
        return redisTemplate.delete(tokenKey);
    }

    /**
     * 根据 userId 构建token信息
     *
     * @param userId
     * @return
     */
    public String buildLoginUserToken(Long userId) {

        String userIdString = String.valueOf(userId);
        AES aes = SecureUtil.aes(systemProperties.getAesSecret().getBytes());
        String subString = aes.encryptHex(userIdString);

        // token
        JwtClaims jwtClaims = JwtUtil.createJwtClaims(subString);
        jwtClaims.setIssuer(SystemConstants.APP_NAME);
        String token = null;
        try {
            token = JwtUtil.createJwt(jwtClaims, systemProperties.getJwtSecret());
        } catch (Exception e) {
            log.error("处理登录token异常", e);
            MyAssert.throwException("处理登录token异常");
        }

        return token;
    }

    /**
     * 构建返回对象
     *
     * @param systemUser systemUser
     * @return LoginUserVO
     */
    public LoginUserVO buildLoginUserVO(SystemUser systemUser) {
        Long userId = systemUser.getUserId();

        // 获取token,同时将token存到Redis
        String token = buildLoginUserToken(userId);

        // 设置Redis登录信息, 根据用户id设置token缓存，在登录的时候，用于校验，同时可以确保用户只允许登录一个
        String tokenKey = SystemConstants.USER_TOKEN_KEY + userId;
        redisTemplate.opsForValue().set(tokenKey, token);
        redisTemplate.expire(tokenKey, SystemConstants.USER_TOKEN_EXPIRE, TimeUnit.SECONDS);

        // 返回对象
        LoginUserVO loginUserVO = new LoginUserVO();
        loginUserVO.setToken(token);
        loginUserVO.setId(userId);
        loginUserVO.setUsername(systemUser.getUsername());
        loginUserVO.setNickname(systemUser.getNickname());

        return loginUserVO;
    }

    public static void main(String[] args) throws InvalidJwtException {
//        HashMap<String, Object> payloadMap = new HashMap<String, Object>();
//        payloadMap.put("token", SystemConstants.HEADER_AUTHORIZATION);
//        String token = JWTUtil.createToken(payloadMap, "CaseIamAFox".getBytes());
//        System.out.println(token);
//        String s = "1234567891234567";
//        System.out.println(s);
//        AES aes = SecureUtil.aes(s.getBytes());
//
//        String subString = aes.encryptHex("3234234");
//        System.out.println(subString);
//
//        String json = aes.decryptStr(subString);
//        System.out.println(json);


        String jwt = "..-Ihss";

        JwtClaims jwtClaims = JwtUtil.getJwtClaims(jwt, "");
        System.out.println(jwtClaims.getRawJson());


    }

}
